package com.fan.cachewebview.core.interceptor

import android.util.Log
import android.util.LruCache
import com.fan.cachewebview.bean.WebResource
import com.fan.cachewebview.core.CacheConfig
import javax.security.auth.Destroyable

/**
 * @description $
 * @date: 2022/2/28 17:24
 * @author: fan
 */
class MemInterceptor constructor(cacheConfig: CacheConfig) : ResourceInterceptor, Destroyable {

    var mLruCache: LruCache<String, WebResource>? = null

    init {
        var memorySize = cacheConfig.getMemCacheSize()
        if (memorySize > 0) {
            mLruCache = ResourceMemCache(memorySize)
        }
    }

    companion object {
        @Volatile
        var instance: MemInterceptor? = null

        fun getInstance(config: CacheConfig): MemInterceptor {
            if (instance == null) {
                synchronized(MemInterceptor::class) {
                    if (instance == null) {
                        instance = MemInterceptor(config)
                    }
                }
            }
            return instance!!
        }
    }


    override fun load(chain: Chain): WebResource? {
        var request = chain.getRequest()
        if (mLruCache != null) {
            var resource: WebResource? = mLruCache!!.get(request?.key)
            if (checkResourceValid(resource)) {
//                Log.d("fan123", "mem cache get:" + request?.url)
                return resource
            }
        }
        var resource: WebResource? = chain.process(request)
        if (mLruCache != null && checkResourceValid(resource) && resource?.isCacheable == true) {
            mLruCache?.put(request?.key, resource)
        }
        return resource
    }


    open class ResourceMemCache constructor(maxSize: Int) : LruCache<String, WebResource>(maxSize) {
        override fun sizeOf(key: String?, value: WebResource): Int {
            var size = 0
            if (value.originBytes != null) {
                size = value.originBytes.size
            }
            return size
        }
    }


    private fun checkResourceValid(resource: WebResource?): Boolean {
        return resource?.originBytes != null && resource.originBytes.size >= 0 && resource.responseHeaders != null
                && resource.responseHeaders.isNotEmpty()
                && resource.isCacheByOurseleves
    }


}